package com.fan.analysis.module.preprocessing.call.service;

import com.fan.analysis.common.domain.ResponseDTO;
import com.fan.analysis.module.preprocessing.call.constant.CallResponseCodeConst;
import com.fan.analysis.module.preprocessing.call.dao.CallDao;
import com.fan.analysis.module.preprocessing.call.domain.entity.CallRecordInCompleteEntity;
import com.fan.analysis.module.preprocessing.call.domain.vo.CallRecordInCompleteVo;
import com.fan.analysis.util.SmartBeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 通话记录服务类
 *
 * @author fan
 * @date 2021/09/20 12:56
 **/
@Slf4j
@Service
public class CallService {

    @Autowired
    private CallDao callDao;



    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<List<CallRecordInCompleteVo>> completingCallRecordData(Integer number) {

        // -------------- 1、获取20条未处理补齐的数据（flag=0），循环遍历进行处理 ------------------------
        List<CallRecordInCompleteVo> callRecordInCompleteVos = callDao.listByNum(number);

        for (CallRecordInCompleteVo callRecordInCompleteVo : callRecordInCompleteVos) {

            // -------------- 2、补齐主叫与被叫 -------------------------------------
            String callingNum = callRecordInCompleteVo.getCallingNum();
            String calledNum = callRecordInCompleteVo.getCalledNum();
            if ("".equals(callingNum) || "".equals(calledNum)) {
                // 主叫和被叫有一个是空值，直接过
                continue;
            }

//            if ("".equals(callingNum)) {// 主叫为空，被叫非空
//
//                // 查询同一时间，主叫为该条记录的被叫的通话记录，如果有，则进行填充
//                CallRecordInCompleteVo byCalledNum = callDao.getByCalledNum(calledNum, callRecordInCompleteVo.getStartTime());
//                if (null != byCalledNum) {
//                    callDao.updateCallingNum(byCalledNum.getCalledNum(), callRecordInCompleteVo.getId());
//                    callRecordInCompleteVo.setCallingNum(byCalledNum.getCalledNum());
//                    callRecordInCompleteVo.getCompletingFields().add("callingNum");
//
//                    // 持续时间有值的话，进行覆盖
//                    if (!"".equals(byCalledNum.getLastTime()) && "".equals(callRecordInCompleteVo.getLastTime())) {
//                        callDao.updateLastTime(byCalledNum.getLastTime(), callRecordInCompleteVo.getId());
//                        callRecordInCompleteVo.setLastTime(byCalledNum.getLastTime());
//                        callRecordInCompleteVo.getCompletingFields().add("lastTime");
//                    }
//
//                } else {
//                    continue;
//                }
//
//            } else if ("".equals(calledNum)) {// 被叫为空，主叫非空
//                // 查询同一时间，被叫为该条记录的主叫的通话记录，如果有，则进行填充
//                CallRecordInCompleteVo byCallingNum = callDao.getByCallingNum(callingNum, callRecordInCompleteVo.getStartTime());
//                if (null != byCallingNum) {
//                    callDao.updateCalledNum(byCallingNum.getCallingNum(), callRecordInCompleteVo.getId());
//                    callRecordInCompleteVo.setCalledNum(byCallingNum.getCallingNum());
//                    callRecordInCompleteVo.getCompletingFields().add("calledNum");
//
//                    // 持续时间有值的话，进行覆盖
//                    if (!"".equals(byCallingNum.getLastTime()) && "".equals(callRecordInCompleteVo.getLastTime())) {
//                        callDao.updateLastTime(byCallingNum.getLastTime(), callRecordInCompleteVo.getId());
//                        callRecordInCompleteVo.setLastTime(byCallingNum.getLastTime());
//                        callRecordInCompleteVo.getCompletingFields().add("lastTime");
//                    }
//                } else {
//                    continue;
//                }
//            }
            // 执行到这里，说明主叫和被叫都不为空
            // -------------- 3、补齐开始时间 ---------------------------------------

            if (null == callRecordInCompleteVo.getStartTime()) {

                // 查询两者之前的通话记录，最近的通话记录的开始时间 + 30分钟
                CallRecordInCompleteVo maxStartTime = callDao.getMaxStartTimeByCallingNumAndCalledNum(callRecordInCompleteVo.getCallingNum(), callRecordInCompleteVo.getCalledNum());

                if (null != maxStartTime) {

                    Date startTime = maxStartTime.getStartTime();
                    long time = 30 * 60 * 1000;//30分钟
                    Date afterDate = new Date(startTime.getTime() + time);//30分钟后的时间

                    callDao.updateStartTime(afterDate, callRecordInCompleteVo.getId());
                    callRecordInCompleteVo.setStartTime(afterDate);
                    callRecordInCompleteVo.getCompletingFields().add("startTime");

                } else {

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date now = new Date();
                    log.info("当前时间：" + sdf.format(now));

                    // 没有查到通话记录，则将当前时间赋值
                    callDao.updateStartTime(now, callRecordInCompleteVo.getId());
                    callRecordInCompleteVo.setStartTime(now);
                    callRecordInCompleteVo.getCompletingFields().add("startTime");
                }

            }

            // -------------- 4、补齐持续时间 ---------------------------------------

            if ("".equals(callRecordInCompleteVo.getLastTime())) {
                // 查询两者之前的通话记录，计算持续时间的平均值
                CallRecordInCompleteVo meanLastTime = callDao.getMeanLastTimeByCallingNumAndCalledNum(callRecordInCompleteVo.getCallingNum(), callRecordInCompleteVo.getCalledNum());
                if (null != meanLastTime) {
                    String lastTime = meanLastTime.getLastTime();
                    callDao.updateLastTime(lastTime, callRecordInCompleteVo.getId());
                    callRecordInCompleteVo.setLastTime(lastTime);
                    callRecordInCompleteVo.getCompletingFields().add("lastTime");


                } else {
                    // 没有查到通话记录，则将持续时间赋值为1分钟
                    callDao.updateLastTime("30", callRecordInCompleteVo.getId());
                    callRecordInCompleteVo.setLastTime("30");
                    callRecordInCompleteVo.getCompletingFields().add("lastTime");
                }

            }

            // -------------- 5、补齐位置 ------------------------------------------
            if ("".equals(callRecordInCompleteVo.getUserLocation())) {

                // 查询主叫之前的通话记录，获取位置的众数
                CallRecordInCompleteVo modeLocation = callDao.getModeLocationByCallingNumAndCalledNum(callRecordInCompleteVo.getCallingNum(), callRecordInCompleteVo.getCalledNum());
                if (null != modeLocation) {

                    String userLocation = modeLocation.getUserLocation();
                    callDao.updateUserLocation(userLocation, callRecordInCompleteVo.getId());
                    callRecordInCompleteVo.setUserLocation(userLocation);
                    callRecordInCompleteVo.getCompletingFields().add("userLocation");
                }
            }

            // -------------- 6、补齐手机型号 ---------------------------------------
            if ("".equals(callRecordInCompleteVo.getMobileType())) {

                // 查询主叫之前的通话记录，获取手机型号的众数
                CallRecordInCompleteVo modeMobileType = callDao.getModeMobileTypeByCallingNumAndCalledNum(callRecordInCompleteVo.getCallingNum(), callRecordInCompleteVo.getCalledNum());
                if (null != modeMobileType) {
                    String mobileType = modeMobileType.getMobileType();
                    callDao.updateMobileType(mobileType, callRecordInCompleteVo.getId());
                    callRecordInCompleteVo.setMobileType(mobileType);
                    callRecordInCompleteVo.getCompletingFields().add("mobileType");
                }
            }

            // 经纬度保留2位小数
            String[] locationSplit = callRecordInCompleteVo.getUserLocation().split(",");

            for (int i = 0; i < locationSplit.length; i++) {
                float v = Float.parseFloat(locationSplit[i]);
                DecimalFormat df = new DecimalFormat("#0.00");
                String result = df.format(v);
                locationSplit[i] = result;
            }
            String locationNew = StringUtils.join(locationSplit, ",");
            callRecordInCompleteVo.setUserLocation(locationNew);

            // 补齐完成记得改变标志位
            callDao.updateFlag(1, callRecordInCompleteVo.getId());
        }


        return ResponseDTO.succData(callRecordInCompleteVos);
    }

    public ResponseDTO<CallRecordInCompleteVo> getInfoById(Long id) {

        CallRecordInCompleteEntity callRecordInCompleteEntity = callDao.selectById(id);
        if (callRecordInCompleteEntity == null) {
            return ResponseDTO.wrap(CallResponseCodeConst.CALL_NOT_EXISTS);
        }
        CallRecordInCompleteVo callRecordInCompleteVo = SmartBeanUtil.copy(callRecordInCompleteEntity, CallRecordInCompleteVo.class);
        return ResponseDTO.succData(callRecordInCompleteVo);
    }

    public ResponseDTO<List<CallRecordInCompleteVo>> listAll() {
        List<CallRecordInCompleteVo> callRecordCompleteVos = callDao.listAll();
        return ResponseDTO.succData(callRecordCompleteVos);
    }
}
